<?php
class LimpiarIndiceTask extends sfBaseTask
{
  protected function configure()
  {
    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application', 'frontend'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environement', 'prod'),
      new sfCommandOption('days', null, sfCommandOption::PARAMETER_REQUIRED, '', 90),
    ));
 
    $this->namespace = 'catalogo';
    $this->name = 'limpiar';
    $this->briefDescription = 'Limpia la bd de articulos';
 
    $this->detailedDescription = <<<EOF
La tarea [catalogo:limpiar|INFO] limpia la bd de articulos:
 
  [./symfony catalogo:limpiar --env=prod --days=90|INFO]
EOF;
  }
 
  protected function execute($arguments = array(), $options = array())
  {
    $databaseManager = new sfDatabaseManager($this->configuration);
   
    // cleanup Lucene index
    $index = ArticuloTable::getLuceneIndex();
   
    $q = Doctrine_Query::create()
      ->from('Articulo a')
      ->where('a.updated_at < ?', date('Y-m-d', time() - 86400 * $options['days']));
   
    $arts = $q->execute();
    foreach ($arts as $art)
    {
      if ($hit = $index->find('pk:'.$art->getId()))
      {
        $index->delete($hit->id);
      }
    }
   
    $index->optimize();
   
    $this->logSection('lucene', 'El indice de Articulos ha sido limpiado y optimizado.');
   
    // Remove stale jobs
    $nb = Doctrine_Core::getTable('Articulo')->cleanup($options['days']);
   
    $this->logSection('doctrine', sprintf('%d articulos han sido eliminados', $nb));
  }
}